﻿using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Threading;
using Framework.Security;
using Interfaces.Enums;
using ServiceInfrastructure.Models.Exceptions;

namespace EconomicInformationServiceWcf.ServiceBehaviours
{
    public class EISAutorizeParameterInspector : IParameterInspector
    {
        private readonly IEnumerable<RoleType> _permission;

        public EISAutorizeParameterInspector(IEnumerable<RoleType> permission)
        {
            _permission = permission;
        }
        
        public object BeforeCall(string operationName, object[] inputs)
        {
            var principal = Thread.CurrentPrincipal as EISSessionPrincipal;

            if(principal == null || _permission == null || !_permission.Any())
                throw new FaultException<SecurityFault>(new SecurityFault("Invalid permissions"));

            var identity = principal.Identity as EISSessionIdentity;
            
             if(identity== null)
                throw new FaultException<SecurityFault>(new SecurityFault("Invalid permissions"));

             if (!ValidatePermission(identity.Session.User.Roles.Select(x => x.Type), _permission)) 
                 throw new FaultException<SecurityFault>(new SecurityFault("Invalid permissions"));
            return null;
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {}

        private static bool ValidatePermission(IEnumerable<RoleType> actual, IEnumerable<RoleType>  expected)
        {
            return expected.Intersect(actual).Any();
        }
    }
}